﻿// Copyright (c) Asicotech.com

using System.Collections.Concurrent;

namespace LaserMark.Components.Events;

/// <summary>
/// IRibbonTabEventBus 接口实现类
/// </summary>
public class RibbonTabEventBus : IRibbonTabEventBus
{
    private ConcurrentDictionary<string, List<Func<RibbonTabEventMessage, Task>>> Subscribers { get; } = new();

    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    /// <param name="eventMessage"></param>
    /// <returns></returns>
    public async Task PublishAsync(RibbonTabEventMessage eventMessage)
    {
        var subscriber = Subscribers.FirstOrDefault(kv => kv.Key == eventMessage.TabItem.Command);
        if (subscriber.Value != null)
        {
            foreach (var handler in subscriber.Value)
            {
                await handler(eventMessage);
            }
        }
    }

    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    /// <param name="@event"></param>
    public void RegisterHandler(RibbonTabEvent @event)
    {
        Subscribers.AddOrUpdate(@event.EventName, key => new List<Func<RibbonTabEventMessage, Task>>() { @event.EventHandler }, (key, handlers) =>
        {
            handlers.Add(@event.EventHandler);
            return handlers;
        });
    }

    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    /// <param name="@event"></param>
    public void UnRegister(RibbonTabEvent @event)
    {
        if (Subscribers.TryGetValue(@event.EventName, out var handlers))
        {
            handlers.Remove(@event.EventHandler);
            if (!handlers.Any())
            {
                Subscribers.Remove(@event.EventName, out _);
            }
        }
    }
}
